import vue from "@vitejs/plugin-vue";
import vueSetupExtend from "vite-plugin-vue-setup-extend";
import removeConsole from "vite-plugin-remove-console";
import mockDevServerPlugin from "vite-plugin-mock-dev-server";
// import { codeInspectorPlugin } from "code-inspector-plugin";
import { defineConfig, loadEnv, ConfigEnv } from "vite";
import { fileURLToPath, URL } from "node:url";

// 当前工作目录路径
const root = process.cwd();

// https://cn.vitejs.dev/config/
export default defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, root); // 加载环境变量
	return {
		plugins: [
			vue(),
			vueSetupExtend(), // 允许在 setup 上添加 name 属性
			mockDevServerPlugin(), // 提供开发环境的 Mock 服务
			// codeInspectorPlugin({ bundler: "vite" }), // 自动定位 DOM 元素在源码的位置
			removeConsole({ includes: ["log", "warn", "info"] }), // 生产环境移除指定的 console 语句
		],
		base: mode.command === "serve" ? "/" : env.VITE_PUBLIC_PATH,
		resolve: {
			alias: {
				"/@": fileURLToPath(new URL("./src", import.meta.url)),
			},
		},
		server: {
			hmr: true, // 热更新
			open: JSON.parse(env.VITE_OPEN), // 自动打开浏览器
			host: "0.0.0.0",
			port: env.VITE_PORT as any,
			proxy: {
				"/mock": { target: "" }, // Mock 专用: https://github.com/pengzhanbo/vite-plugin-mock-dev-server
			},
		},
		css: { preprocessorOptions: { css: { charset: false }, scss: { api: "modern" } } },
		build: {
			outDir: "dist",
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					chunkFileNames: "assets/js/[name]-[hash].js",
					entryFileNames: "assets/js/[name]-[hash].js",
					assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
					manualChunks(id) {
						if (id.includes("node_modules")) {
							return id.toString().split("node_modules/")[1].split("/")[0].toString();
						}
					},
				},
			},
		},
		define: {
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
			__PROJ_NAME__: JSON.stringify(process.env.npm_package_name),
		},
	};
});
